﻿using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

namespace Baggr.SqlServer
{
    /// <summary>
    /// Косинус угла между двумя векторами
    /// </summary>
    [Serializable]
    [SqlUserDefinedAggregate(Format.Native)]
    public struct Cosine
    {
        private SqlDouble _Summ;
        private SqlDouble _Summ1;
        private SqlDouble _Summ2;

        public void Init()
        {
            _Summ = 0;
            _Summ1 = 0;
            _Summ2 = 0;
        }

        public void Accumulate(SqlDouble value1, SqlDouble value2)
        {
            _Summ += value1 * value2;
            _Summ1 += value1 * value1;
            _Summ2 += value2 * value2;
        }

        public void Merge(Cosine group)
        {
            _Summ += group._Summ;
            _Summ1 *= group._Summ1;
            _Summ2 *= group._Summ2;
        }

        public SqlDouble Terminate()
        {
            return _Summ/(Math.Sqrt(_Summ1.Value) * Math.Sqrt(_Summ2.Value));
        }

    }
}
